package com.ls.lserp.modules.material.service;




import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.SpringContextHolder;
import com.ls.lserp.modules.material.dao.MaterialInboundDao;
import com.ls.lserp.modules.material.entity.InventoryRequest;
import com.ls.lserp.modules.material.entity.MaterialOutInbound;
import com.ls.lserp.modules.produce.dao.ProduceNoticeDao;
import com.ls.lserp.modules.produce.entity.ProduceNotice;
import com.ls.lserp.modules.purchase.dao.PurchaseContractDao;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.purchase.entity.PurchaseRequest;
import com.ls.lserp.modules.setting.dao.InventoryWarningDao;

@Service
@Transactional(readOnly = false)
public class MaterialInboundService extends CrudService<MaterialInboundDao,MaterialOutInbound>{

	//合同
	 @Autowired
	 private MaterialInboundDao materialInboundDao ;
	 @Autowired
	 private PurchaseContractDao purchaseContractDao;
	 @Autowired
	 private InventoryWarningDao inventoryWarningDao;
	 //生产通知单
	 @Autowired
	 private ProduceNoticeDao produceNoticeDao;

	 /**
		 * @Title: findList
		 * @Description: 一览查询
		 * @param page
		 * @param orderMateriel
		 * @return Page<OrderMateriel>
		 */
		public Page<MaterialOutInbound> findList(Page<MaterialOutInbound> page, MaterialOutInbound materialOutInbound) {
			
			List<MaterialOutInbound> irDetailList = null;
			BigDecimal tempRequestQuantity = null;
			BigDecimal tempRealQuantity = null;
			BigDecimal tempResidueQuantity = null;
			
			// tab页分，检索条件设定(0:全部,1:待入库,2:已入库)
			materialOutInbound.setInventoryStatus(ResourcesUtil.getConfig("inventory_status_wait"));
			
			// 入出库区分（入库)
			materialOutInbound.setInventoryInOutKbn(ResourcesUtil.getConfig("inventory_in_out_kbn_in"));
						
			
			// 设置分页参数
			materialOutInbound.setPage(page);
			List<MaterialOutInbound> resultList = materialInboundDao.findList(materialOutInbound);
			
			if(!CollectionsUtils.isEmpty(resultList)){
				// 库存申请信息
				for(MaterialOutInbound ir : resultList){
					tempRequestQuantity = new BigDecimal("0");
					tempRealQuantity = new BigDecimal("0");
					tempResidueQuantity = new BigDecimal("0");
					irDetailList = materialInboundDao.findInventoryRequestDetailList(ir);
					if(!CollectionsUtils.isEmpty(irDetailList)){
						// 库存申请明细
						for(MaterialOutInbound ird : irDetailList){
							tempRequestQuantity = tempRequestQuantity.add(checkBigDecimalNull(ird.getRequestQuantity()));
							tempRealQuantity = tempRealQuantity.add(checkBigDecimalNull(ird.getRealQuantity()));
						}
						tempResidueQuantity = tempRequestQuantity.subtract(tempRealQuantity);
						if (tempResidueQuantity.compareTo(BigDecimal.valueOf(0)) == -1) {
							tempResidueQuantity = new BigDecimal("0");
						}
						ir.setRequestQuantity(tempRequestQuantity);
						ir.setRealQuantity(tempRealQuantity);
						ir.setResidueQuantity(tempResidueQuantity);
					}
					
//					if(tempResidueQuantity.doubleValue()>0){
//						ir.setRequestDoneStatus(SpringContextHolder.getApplicationContext().getMessage("inventory_request_status_no",null,null));
//					}else{
//						ir.setRequestDoneStatus(SpringContextHolder.getApplicationContext().getMessage("inventory_request_status_all",null,null));
//					}
				}
			}
			
	        // 执行分页查询
	        page.setList(resultList);
	        
	        return page;
		}
		/**
		 * check BigDecimal
		 * @param cost
		 * @return 取不到返回0
		 */
		public BigDecimal checkBigDecimalNull(BigDecimal cost){
			if(cost==null){
				return new BigDecimal("0");
			}
			return cost;
		}
		
	    /**
	     * @Title: findRequestDetailsList
	     * @Description: 入库申请明细
	     * @param @param materialOutInbound
	     * @param @return
	     * @return List<MaterialOutInbound>
	     * @throws
	     */
	   
	   public List<MaterialOutInbound> findRequestDetailsList(MaterialOutInbound materialOutInbound) {
	       return materialInboundDao.findRequestDetailsList(materialOutInbound);
	   }
	   /**
	     * @Title: findRequestDetailsList
	     * @Description: 库存明细
	     * @param @param materialOutInbound
	     * @param @return
	     * @return List<MaterialOutInbound>
	     * @throws
	     */
	   
	   public List<MaterialOutInbound> findInventoryMaterialDetailList(MaterialOutInbound materialOutInbound) {
	       return materialInboundDao.findInventoryMaterialDetailList(materialOutInbound);
	   }
	   /**
		  * @Title: findRequestDetailsList
		  * @Description: 仓库集
		  * @param @param materialOutInbound
		  * @param @return
		  * @return List<MaterialOutInbound> 
		  * @throws
		  */
		public List<MaterialOutInbound> findWarehouseList(MaterialOutInbound materialOutInbound){
			return materialInboundDao.findWarehouseList(materialOutInbound);
		}
		/**
		  * @Title: findRequestDetailsList
		  * @Description: 货架集
		  * @param @param materialOutInbound
		  * @param @return
		  * @return List<MaterialOutInbound> 
		  * @throws
		  */
		public List<MaterialOutInbound> findRackList(MaterialOutInbound materialOutInbound){
			return materialInboundDao.findRackList(materialOutInbound);
		}
		     
		/**
		   * @Title: saveDetail
		   * @Description: 保存入库货架
		   * @param @param materialOutInbound
		   * @return void 
		   * @throws
		   */
		  @Transactional(readOnly = false)
		  public void saveDetail(MaterialOutInbound materialOutInbound) {
			  materialOutInbound.preInsert();
			  materialInboundDao.insertDetail(materialOutInbound);
			  String realQuantityNew = materialOutInbound.getInventoryQuantity();
			  MaterialOutInbound materialNew = materialInboundDao.getQuantity(materialOutInbound);
			  String realQuantity = materialNew.getInventoryQuantity();
			  realQuantity = (new BigDecimal(realQuantity)).add(new BigDecimal(realQuantityNew))+"";
			  materialOutInbound.setInventoryQuantity(realQuantity);
			  materialInboundDao.updateQuantity(materialOutInbound);
		  }
		  
		  /**
		   * @Title: saveDetail
		   * @Description: 保存实际数量
		   * @param @param materialOutInbound
		   * @return void 
		   * @throws
		   */
		  @Transactional(readOnly = false)
		  public void saveQuantity(MaterialOutInbound materialOutInbound) {
			  materialOutInbound.preInsert();
			  materialInboundDao.updateDetail(materialOutInbound);
		  }
		  /**
		   * @Title: saveDetail
		   * @Description: 更新状态
		   * @param @param materialOutInbound
		   * @return void 
		   * @throws
		   */
		  @Transactional(readOnly = false)
		  public void changeStatus(MaterialOutInbound materialOutInbound) {
			  materialOutInbound.preInsert();
			  //materialOutInbound.setInventoryStatus(ResourcesUtil.getConfig("inventory_status_done"));
			  materialInboundDao.changeStatus(materialOutInbound);
			  if ("INVENTORY_STATUS-STATUS_30".equals(materialOutInbound.getInventoryStatus())) {
				  List<PurchaseRequest> detailList = materialInboundDao.findListByID(materialOutInbound.getId());
				  for (int i = 0; i < detailList.size(); i++) {
					  if (detailList.get(i)!=null) {
						  if (i==0) {
							  materialInboundDao.updateContractStatus(detailList.get(i));
						  }
						  materialInboundDao.updateContractDetailStatus(detailList.get(i));
						  ProduceNotice produceNotice = new ProduceNotice();
						  //获取订单ID
						  Long indentId =  materialInboundDao.getIndentID(detailList.get(i));
						  long okCount = 0;
						  //如果订单ID存在则更新核料预定耗料表状态
						  if (indentId != null) {
							  materialInboundDao.updaterReserverPurchaseStatus(detailList.get(i));
							  okCount = materialInboundDao.getCount(indentId);
							  if (okCount == 0) {
								  produceNotice.preInsert();
								  produceNotice.setMaterialStatus(1);
								  produceNotice.setIndentID(indentId);
								  produceNoticeDao.updateStatusByIndentID(produceNotice);
							  }
						  }
					}
				}
			  }
		  }
		  
		  /**
		   * 更新面料库存预警状态
		   * @param materialId
		   * @param venderId
		   * @throws SQLException
		   */
		  public void updateStatus(String materialId,String venderId) throws SQLException{
			  purchaseContractDao.updateReserverPurchaseStatus(materialId, venderId,"4",ResourcesUtil.getConfig("inventoryAlert_10"));
			  List<PurchaseContract> pList =  purchaseContractDao.findReserverPurchaseList(materialId,ResourcesUtil.getConfig("inventoryAlert_10"));
			  String updateFlag = "true";
			  if (pList != null && pList.size() > 0) {
				  for (PurchaseContract pContract : pList) {
					  if (!"4".equals(pContract.getMaterialStatus())) {
						  updateFlag = "false";
					  }
				  }
				  if ("true".equals(updateFlag)) {
					  inventoryWarningDao.updateAlertStatus(materialId,ResourcesUtil.getConfig("inventoryAlert_20"),ResourcesUtil.getConfig("inventoryAlert_10"));
				  }
			  }
		  }
}
